﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogic;
using BusinessObject;
using Utility;
using System.Web.Security;
using System.Resources;
namespace WebTeamplate
{

    public partial class Admin_DMPhieuBanHang : BasePage
    {
        #region Fields
        public string urlDetail = "ChiTietPhieuBanHang.aspx";
        public double thanhTien;
        public string strThanhTien = string.Empty;
        public string strCurrency = string.Empty;
        int count = 0;

        #endregion

        #region ViewState
        public int PageIndex
        {

            get
            {

                object o = ViewState["PageIndex"];

                if (o != null) return (int)o;

                return 0;

                //a default

            }

            set { ViewState["PageIndex"] = value; }

        }
        public string SortField
        {

            get
            {
                object o = ViewState["SortField"];
                if (o != null) return (string)o;
                return string.Empty;
            }

            set { ViewState["SortField"] = value; }

        }
        public string SortExpression
        {

            get
            {
                object o = ViewState["SortExpression"];
                if (o != null) return (string)o;
                return string.Empty;
            }

            set { ViewState["SortExpression"] = value; }

        }
        #endregion

        #region Init,Load
        protected void Page_Load(object sender, EventArgs e)
        {
            ClientDefaultButton.SetPageDefaultButton(this.Page, btnSearch.ClientID);
            if (!Page.IsPostBack)
            {
                InitData();
                GetDefaultData();
                LoadData();

            }

        }
        private void GetDefaultData()
        {
            //get query paramate
            try
            {
                drlKho.SelectedValue = CommonFunction.GetValueFromQueryString(this.Page, "kho");
            }
            catch
            {
            }            
            txtMaMatHang.Text = CommonFunction.GetValueFromQueryString(this.Page, "mamh");
            txtMaPhuTung.Text = CommonFunction.GetValueFromQueryString(this.Page, "mapt");
            txtNgayLapPhieuFrom.Text = CommonFunction.GetValueFromQueryString(this.Page, "sdate");
            txtNgayLapPhieuTo.Text = CommonFunction.GetValueFromQueryString(this.Page, "edate");
           
        }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitTextControl();
            this.imgNgayNhapSortDown.ImageUrl = CommonFunction.DEFAULT_SORTDOWN_IMAGEURL;
            this.imgNgayNhapSortUp.ImageUrl = CommonFunction.DEFAULT_SORTUP_IMAGEURL;
            this.imgKhoSortDown.ImageUrl = CommonFunction.DEFAULT_SORTDOWN_IMAGEURL;
            this.imgKhoSortUp.ImageUrl = CommonFunction.DEFAULT_SORTUP_IMAGEURL;

            this.imgNguoiLapPhieuSortDown.ImageUrl = CommonFunction.DEFAULT_SORTDOWN_IMAGEURL;
            this.imgNguoiLapPhieuSortUp.ImageUrl = CommonFunction.DEFAULT_SORTUP_IMAGEURL;

            this.imgMaPhieuSortDown.ImageUrl = CommonFunction.DEFAULT_SORTDOWN_IMAGEURL;
            this.imgMaPhieuSortUp.ImageUrl = CommonFunction.DEFAULT_SORTUP_IMAGEURL;



            this.imgThanhTienSortDown.ImageUrl = CommonFunction.DEFAULT_SORTDOWN_IMAGEURL;
            this.imgThanhTienSortUp.ImageUrl = CommonFunction.DEFAULT_SORTUP_IMAGEURL;

            imgNgayNhapSortDown.Click += new ImageClickEventHandler(imgNgayNhapSortDown_Click);
            imgNgayNhapSortUp.Click += new ImageClickEventHandler(imgNgayNhapSortUp_Click);
            imgKhoSortDown.Click += new ImageClickEventHandler(imgKhoSortDown_Click);
            imgKhoSortUp.Click += new ImageClickEventHandler(imgKhoSortUp_Click);
            imgNguoiLapPhieuSortDown.Click += new ImageClickEventHandler(imgNguoiLapPhieuSortDown_Click);
            imgNguoiLapPhieuSortUp.Click += new ImageClickEventHandler(imgNguoiLapPhieuSortUp_Click);
            imgThanhTienSortUp.Click += new ImageClickEventHandler(imgThanhTienSortUp_Click);
            imgThanhTienSortDown.Click += new ImageClickEventHandler(imgThanhTienSortDown_Click);
            imgMaPhieuSortDown.Click += new ImageClickEventHandler(imgMaPhieuSortDown_Click);
            imgMaPhieuSortUp.Click += new ImageClickEventHandler(imgMaPhieuSortUp_Click);
        }

        void imgMaPhieuSortUp_Click(object sender, ImageClickEventArgs e)
        {
            this.SortField = "MaSoPhieu";
            this.SortExpression = CommonFunction.DEFAULT_SORTUP_EXPRESSION;
            LoadData();
        }

        void imgMaPhieuSortDown_Click(object sender, ImageClickEventArgs e)
        {
            this.SortField = "MaSoPhieu";
            this.SortExpression = CommonFunction.DEFAULT_SORTDOWN_EXPRESSION;
            LoadData();
        }

        void imgThanhTienSortDown_Click(object sender, ImageClickEventArgs e)
        {
            this.SortField = "tongGiaTien";
            this.SortExpression = CommonFunction.DEFAULT_SORTDOWN_EXPRESSION;
            LoadData();
        }

        void imgThanhTienSortUp_Click(object sender, ImageClickEventArgs e)
        {
            this.SortField = "tongGiaTien";
            this.SortExpression = CommonFunction.DEFAULT_SORTUP_EXPRESSION;
            LoadData();
        }

        void imgNguoiLapPhieuSortUp_Click(object sender, ImageClickEventArgs e)
        {
            this.SortField = "p.Name";
            this.SortExpression = CommonFunction.DEFAULT_SORTUP_EXPRESSION;
            LoadData();
        }

        void imgNguoiLapPhieuSortDown_Click(object sender, ImageClickEventArgs e)
        {
            this.SortField = "p.Name";
            this.SortExpression = CommonFunction.DEFAULT_SORTDOWN_EXPRESSION;
            LoadData();
        }

        void imgKhoSortUp_Click(object sender, ImageClickEventArgs e)
        {
            this.SortField = "k.SubCategoryName";
            this.SortExpression = CommonFunction.DEFAULT_SORTUP_EXPRESSION;
            LoadData();
        }

        void imgKhoSortDown_Click(object sender, ImageClickEventArgs e)
        {
            this.SortField = "k.SubCategoryName";
            this.SortExpression = CommonFunction.DEFAULT_SORTDOWN_EXPRESSION;
            LoadData();
        }
        #endregion

        #region Methods
        private void CheckValidKho()
        {
            // MembershipUser userLogin=Membership.GetUser(this.userloginId);
            if (Roles.IsUserInRole(userLoginName, CommonFunction.ROLES_SALE))
            {
                UserProfile user = UserProfileUtil.Get(this.applicationName, UserloginId);
                if (user == null)
                    return;
                ListItemCollection itemDelete = new ListItemCollection();
                foreach (ListItem item in drlKho.Items)
                {
                    if (item.Value.Trim().ToLower() != user.MaKho.ToString().ToLower())
                    {
                        itemDelete.Add(item);
                    }
                }
                foreach (ListItem item in itemDelete)
                {
                    drlKho.Items.Remove(item);
                }
            }
        }
        public void InitTextControl()
        {
            btnSearch.Text = Resources.Resource.LABEL_BUTTON_SEARCH;
            btnReset.Text = Resources.Resource.LABEL_BUTTON_RESET;
            btnAddNew.Text = Resources.Resource.LABEL_BUTTON_ADDNEW;
            btnDelete.Text = Resources.Resource.LABEL_DELETE;
            this.SortExpression = "DESC";
            this.SortField = "NgayLapPhieu";
        }
        private void InitData()
        {
            vsumSumary.ValidationGroup = cusvNgayLapPhieuFrom.ValidationGroup = cusvNgayLapPhieuTo.ValidationGroup = btnSearch.ValidationGroup = "phieuhang";
            cusvNgayLapPhieuFrom.ErrorMessage = cusvNgayLapPhieuTo.ErrorMessage = string.Format(Resources.Resource.MESSAGE_VALIDATE_INPUT, CommonFunction.GetTextLabel(lblNgayNhap));
            cusvNgayLapPhieuFrom.ValidationGroup = cusvNgayLapPhieuTo.ValidationGroup = "phieuhang";
            this.PageIndex = 1;
            Pager1.PageSize = CommonFunction.DEFAULT_ADMIN_PAGE_SIZE;
            Pager2.PageSize = CommonFunction.DEFAULT_ADMIN_PAGE_SIZE;
            CommonFunction.LoadSubCate(drlKho, CommonFunction.DEFAULT_WAREHOUSE_CODE, false);
            CheckValidKho();

        }

        void imgNgayNhapSortUp_Click(object sender, ImageClickEventArgs e)
        {
            this.SortField = "NgayLapPhieu";
            this.SortExpression = CommonFunction.DEFAULT_SORTUP_EXPRESSION;
            LoadData();
        }

        void imgNgayNhapSortDown_Click(object sender, ImageClickEventArgs e)
        {
            this.SortField = "NgayLapPhieu";
            this.SortExpression = CommonFunction.DEFAULT_SORTDOWN_EXPRESSION;
            LoadData();
        }

        public void LoadData()
        {
            thanhTien = 0;
            hidListId.Value = string.Empty;
            hidListIdSelect.Value = string.Empty;
            PhieuBanHang objPhieuBan = new PhieuBanHang();
            objPhieuBan.ObjectSortOrder.SortExpression = this.SortExpression;
            objPhieuBan.ObjectSortOrder.SortField = this.SortField;
            objPhieuBan.ObjectPaging.PageIndex = this.PageIndex;
            objPhieuBan.ObjectPaging.PageSize = Pager1.PageSize;
            //objPhieuNhap.Condition = " where categoryId='" + CommonFunction.DEFAULT_WAREHOUSE_CODE + "'";
            objPhieuBan.Condition = " where 1=1 ";
            if (txtSoPhieu.Text != string.Empty)
                objPhieuBan.Condition += " and ph.MaSoPhieu=" + txtSoPhieu.Text.Trim();
            if (drlKho.SelectedValue != string.Empty)
                objPhieuBan.Condition += " and ph.maKho=" + drlKho.SelectedValue;

            if (txtMaMatHang.Text != string.Empty)
                objPhieuBan.Condition += " and [dbo].[fcMaMatHangInPhieuBanHang]('" + txtMaMatHang.Text.Trim() + "',ph.MaPhieuBanHang)=1";
            if (txtMaPhuTung.Text != string.Empty)
                objPhieuBan.Condition += " and [dbo].[fcMaPhuTungInPhieuBanHang]('" + txtMaPhuTung.Text.Trim() + "',ph.MaPhieuBanHang)=1";

            if (txtNgayLapPhieuFrom.Text != string.Empty)
            {
                DateTime dt = ConvertValueObject.ParseDateTime(txtNgayLapPhieuFrom.Text);
                objPhieuBan.Condition += " and DATEDIFF(day,'" + dt.Year + "-" + dt.Month + "-" + dt.Day + "',ph.NgayLapPhieu)>=0";
            }
            if (txtNgayLapPhieuTo.Text != string.Empty)
            {
                DateTime dt = ConvertValueObject.ParseDateTime(txtNgayLapPhieuTo.Text);
                objPhieuBan.Condition += " and DATEDIFF(day,'" + dt.Year + "-" + dt.Month + "-" + dt.Day + "',ph.NgayLapPhieu)<=0";
            }
            List<PhieuBanHangResult> lstResult = PhieuBanHangUtil.SearchPhieuBanHangSomeCondition(objPhieuBan);
            if (lstResult != null && lstResult.Count > 0)
                count = lstResult.Count;
            rptData.DataSource = lstResult;
            rptData.DataBind();
            Pager1.SetPaging(this.PageIndex, count, objPhieuBan.ToltalRow);
            Pager2.SetPaging(this.PageIndex, count, objPhieuBan.ToltalRow);
            strThanhTien = ConvertValueObject.ParseString(thanhTien) + " " + strCurrency;
        }
        private void Delete(string id)
        {
            if (PhieuBanHangUtil.Delete(ConvertValueObject.ParseLong(id)))
                LoadData();
        }


        #endregion

        #region Events,Handler
        protected void drlLanguage_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadData();
        }
        protected void rptData_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                PhieuBanHangResult cate = (PhieuBanHangResult)e.Item.DataItem;
                if (cate == null)
                    return;
                
                Literal ltr = (Literal)e.Item.FindControl("ltrNo");
                ltr.Text = (e.Item.ItemIndex + 1).ToString();

                //ltr = (Literal)e.Item.FindControl("ltrSubCode");
                string url = urlDetail + "?id=" + cate.MaPhieuBanHang + "&act=" + CommonFunction.DEFAULT_COMMAND_EDIT;
                //ltr.Text = "<a href='" + url + "'>" + Server.HtmlEncode(cate.SubCategoryCode) + "</a>";
                ltr = (Literal)e.Item.FindControl("ltrNgayLap");
                ltr.Text = ConvertValueObject.ParseString(cate.NgayLapPhieu);

                ltr = (Literal)e.Item.FindControl("ltrNguoiLap");
                ltr.Text = cate.NguoiLapPhieu;
                MembershipUser member = Membership.GetUser(cate.NguoiLapPhieu);
                if (member != null)
                {
                    UserProfile user = UserProfileUtil.Get(this.applicationName, new Guid(member.ProviderUserKey.ToString()));
                    if (user != null)
                        ltr.Text = user.Name;
                    else ltr.Text = cate.NguoiLapPhieu;
                }
                else ltr.Text = cate.NguoiLapPhieu;

                ltr = (Literal)e.Item.FindControl("ltrKho");
                ltr.Text = Server.HtmlEncode(cate.TenKho.ToString());
                ltr = (Literal)e.Item.FindControl("ltrThanhTien");
                if (!cate.IsVAT)
                {
                    ltr.Text = ConvertValueObject.ParseString(cate.TongGiaTien);
                    thanhTien += cate.TongGiaTien;
                }
                else
                {
                    double tienVAT = cate.TongGiaTien * cate.VAT;
                    ltr.Text = ConvertValueObject.ParseString(tienVAT);
                    thanhTien += tienVAT;
                }
                Curency objCurency = PhieuBanHangUtil.GetCurencyForPhieuBanHang(cate.MaPhieuBanHang);
                if (objCurency != null)
                    ltr.Text += " " + objCurency.Name;
                strCurrency = objCurency.Name;
                ImageButton imgButton = (ImageButton)e.Item.FindControl("btnPublish");
                imgButton.CommandArgument = cate.MaPhieuBanHang.ToString();
                ltr = (Literal)e.Item.FindControl("ltrStatus");               
                HyperLink hplEdit = (HyperLink)e.Item.FindControl("hplEdit");
                hplEdit.NavigateUrl = url;
                LinkButton lbtnDelete = (LinkButton)e.Item.FindControl("lbtnDelete");
                lbtnDelete.Text = Resources.Resource.LABEL_DELETE;
                lbtnDelete.CommandArgument = cate.MaPhieuBanHang.ToString();
                hidListId.Value += cate.MaPhieuBanHang + ";";
                if (cate.IsCommit)
                {
                    imgButton.Visible = false;
                    ltr.Text = "Đã chốt sổ";
                    lbtnDelete.Visible = false;
                    hplEdit.Visible = false;
                }
                else
                {
                    hplEdit.Visible = true;
                    imgButton.ImageUrl = CommonFunction.DEFAULT_DEACTIVE_IMAGEURL;
                    ltr.Text = "Chưa chốt sổ";
                    lbtnDelete.Visible = true;
                }
            }
        }
        protected void rptData_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            string id = e.CommandArgument.ToString();
            switch (e.CommandName)
            {

                case "delete":
                    {
                        Delete(id);
                        break;
                    }

            }

        }


        protected void btnSearch_Click(object sender, EventArgs e)
        {
            this.SortExpression = "ASC";
            this.SortField = "[Order]";
            //reset sort order
            this.PageIndex = 1;
            LoadData();
        }


        protected void Pager1_PageIndexChanging(object obj, PagerControl.PageIndexChangeEventArgs e)
        {
            this.PageIndex = e.newPageIndex;
            LoadData();
        }
        protected void Pager1_PageSizeChanging(object obj, PagerControl.PageSizeChangeEventArgs e)
        {
            this.PageIndex = 1;
            //  this.PageSize = e.newPageSize;
            Pager2.PageSize = e.newPageSize;
            LoadData();
        }
        protected void Pager2_PageSizeChanging(object obj, PagerControl.PageSizeChangeEventArgs e)
        {
            this.PageIndex = 1;
            //  this.PageSize = e.newPageSize;
            Pager1.PageSize = e.newPageSize;
            LoadData();
        }
        protected void btnAddNew_Click(object sender, EventArgs e)
        {
            Response.Redirect(urlDetail);
        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            string[] arr = hidListIdSelect.Value.Split(';');
            for (int i = 0; i < arr.Length - 1; i++)
            {
                if (arr[i].ToString() != string.Empty)
                    PhieuBanHangUtil.Delete(ConvertValueObject.ParseInt(arr[i].ToString()));
            }
            LoadData();
        }
        #endregion
    }
}
